function [part] = make_cv_partition(n, n_folds)
% MAKE_XVAL_PARTITION - Randomly generate cross validation partition.
%
% Usage:
% 
%  PART = MAKE_CV_PARTITION(N, N_FOLDS)
%
% Randomly generates a partitioning for N datapoints into N_FOLDS equally
% sized folds (or as close to equal as possible). PART is a 1 X N vector,
% where PART(i) is a number in (1...N_FOLDS) indicating the fold assignment
% of the i'th data point.

%Calculate the number of points in each fold
fold_size = floor(n/n_folds);

%Perform random permutations on the values 1:n_folds
perm_vect_short = randperm(n_folds);

%Make a new array that is the perm_vect_short repeated fold_size times. This
%array will have each number in the set {1,...,n_folds} exactly fold_size
%times. Note that perm_vect_long will have exactly n elements.
perm_vect_long = repmat(perm_vect_short, [1 fold_size]);

%If n_folds is not a divisor of n (i.e. if fold_size is not an integer
%before the 'floor' command), add in the appropriate number of (random)
%elements to perm_vect_long.
diff = n-size(perm_vect_long,2);
if diff > 0
    perm_vect_long = cat(2, perm_vect_long, perm_vect_short(1:diff));
end    

%Permute perm_vect_long so that the order is random. This is accomplished
%by indexing the vector with a random number, generated by
%randperm(length(perm_vect_long)).
part = perm_vect_long(randperm(n));


